<template>
  <div id="taskManagementLog" style="padding-top:20px;">
    <div class="safeEvents-content">
      <!-- 主显示区 -->
      <div class="main-wrap">
        <div id="operation-wrap">
          <at-button @click="stateCtrl.fileExportVisible=true;(totalSelectedItem.length>0) ? (exportInfo.amount = '1') : (exportInfo.amount = '2')" type="primary"><i class="saas-icon-res-right"></i>导出</at-button>
        </div>
        <!-- 主列表 -->
        <div class="table-main-wrap">
            <!-- v-loading="loadingCtrl.isTableLoading" element-loading-text="拼命加载中" -->
          <at-table ref="log" id="table-main" :data="tableData" @sort-change="handleSortChange" @selection-change="handleSelectionChange" @cell-click="jumpDetail"  :row-key="getRowKeys">
            <at-table-column type="selection" width="60" :reserve-selection="true"></at-table-column>
            <at-table-column prop="_source.ts" label="发生时间" width="180" sortable>
              <template slot-scope="scope">
                <span>{{scope.row._source.ts}}</span>
              </template>
            </at-table-column>
            <at-table-column prop="_source.sys_info.name" label="系统名称" width="200"  show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{scope.row._source.sys_info === undefined ? '未注册资产': (scope.row._source.sys_info.name === null || scope.row._source.sys_info.name === '' || scope.row._source.sys_info.name === undefined)? '未注册资产' : scope.row._source.sys_info.name}}</span>
                </template>
            </at-table-column>
            <at-table-column prop="_source.level" label="严重级别" width="110" v-if="logType!=='visible'" sortable>
                <template slot-scope="scope">
                  <span v-if="scope.row._source.level" :class="['level-tag',scope.row._source.level === 0?'level-tag-normal':scope.row._source.level === 1?'level-tag-low-risk':scope.row._source.level === 2?'level-tag-middle-risk':scope.row._source.level === 3?'level-tag-high-risk':'level-tag-serious']">
                      {{scope.row._source.level === undefined ? ' ': `${translateChinese('levelStr',scope.row._source.level)}`}}
                  </span>
                  <span class="level" v-else>--</span>  
                </template>
            </at-table-column>
            <at-table-column prop="_source.describes" label="日志描述" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{scope.row._source.describes}}</span>
                </template>
            </at-table-column>
            <at-table-column prop="_source.stype" label="日志类型" show-overflow-tooltip width="140">
              <template slot-scope="scope">
                <span v-html="translateChinese('stype', scope.row._source.stype, stypeDict)"></span>
              </template>
          </at-table-column>
            <at-table-column prop="_source.sys_info.unit" label="监测单位" width="140" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{scope.row._source.sys_info.unit === undefined ? '' : scope.row._source.sys_info.unit}}</span>
                </template>
            </at-table-column>
          </at-table>
        </div>
        <!-- 分页器 -->
        <div id="bottom">
          <span class="pageSign">
              <at-tooltip content="数据量过大，只显示前9900条" placement="top" v-if="pagination.total>9900">
                <i class="btn-info"></i>
              </at-tooltip>
          </span>
          <div class="pageWrap">
            <Pagination  :currentPage="pagination.currentPage" :total="pagination.total>9900?9900:pagination.total" :pageSizes="[20, 40, 60, 80]" :pageSize="pagination.pageSize" layout="slot, total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" ref="aaa">
            </Pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 导出对话框 -->
    <at-dialog title="导出" class="file-export" :visible.sync="stateCtrl.fileExportVisible">
      <div class="dialog-body">
        <tr>
          <td class="body-title">导出范围</td>
          <td class="item"><at-radio-wall v-model="exportInfo.amount" label="1">导出选中</at-radio-wall></td>
          <td><at-radio-wall v-model="exportInfo.amount" label="2">导出全部（最多10000条）</at-radio-wall></td>
        </tr>
        <tr>
          <td class="body-title">导出格式</td>
          <td class="item"><at-radio-wall v-model="exportInfo.type" label="3">Excel导出</at-radio-wall></td>
          <td><at-radio-wall v-model="exportInfo.type" label="4">JSON格式导出</at-radio-wall></td>
        </tr>
      </div>
      <div slot="footer" class="dialog-footer">
        <at-button type="primary" @click="confirmExportEvent">确 定</at-button>
      </div>
    </at-dialog>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapGetters, mapState } from 'vuex'
import { getProjectConfig } from './config'
import { detailInfoStructure, mixin } from '../../../../models/safeEvents/utils/util'
import { setCondition } from '../../../../models/taskManagementLog/utils/esSearch'
import { initDetail } from '../../../../models/safeEvents/utils/initDetail'
export default {
  mixins: [mixin],
  data () {
    return {
      // 返回table row.id 用于导出
      getRowKeys (row) {
        return row._id
      },
      // 项目控制
      projectCtrl: {
        btnExport: false,
        btnImport: false,
        btnUserInsert: false
      },
      stateCtrl: {
        // 搜索框清空按钮
        btnClearVisible: false,
        // 高度auto的index
        moreCtrl: null,
        // 显示“更多按钮“的index
        btnMoreCtrl: null,
        // 导出对话框
        fileExportVisible: false,
        // 过滤条件
        filterGroupVisible: false,
        // 过滤对话框
        filterDialogVisible: false,
        // 标签聚合
        labelGroupVisible: false,
        // 标签聚合是否打开过
        isExpandLabelGroup: false,
        // 上次打开过的聚合详情的index
        hasExpandGroupDetail: null
      },
      // 导入loading
      loading: {},
      // 导入验证信息
      importError: '',
      // 导入验证错误条数
      importErrorCount: 0,
      // 筛选条件类别  用于"更多"对话框
      dialogType: '',
      // 筛选条件类别index
      dialogIndex: 0,
      // 聚合tab当前active的index
      activeIndex: -1,
      // 导入的文件
      fileList: [],
      tabTypeShow: 'zhu',
      // 当前主table勾选的数据
      currSelectedItem: [],
      // 所有页中table勾选的数据
      totalSelectedItem: [],
      // 导出选项
      exportInfo: {
        amount: '1', // 默认导出选中
        type: '3' // 默认以excel形式导出
      },
      // 上次点击过的详情id
      lastId: '',
      // 日志详情数据
      detailRawData: {},
      // 日志详情source数据
      detailHandleData: {
        status: false,
        projectCtrl: {}
      },
      groupItem: 'groupItem'
    }
  },
  created () {
    // 项目配置
    let projectConfig = this.getProjectConfig(this.project.name)
    for (let index in projectConfig) {
      this.projectCtrl[index] = projectConfig[index]
    }
    // 设置检测日志类型
    this.SET_LOGTYPE('all')
    // 设置ess搜索类型
    setCondition('all')
    this.searchInput = `task_id:${this.$route.path.split('/')[4]}`
    this.SET_SEARCHINPUT_ES(this.searchInput)
    this.SET_LAST_LOGTYPE('all')
    // 获取日志类型中英对照
    this.GET_STYPE_DICT()
    this.onSearch('search')
  },
  mounted () {
  },
  methods: {
    ...mapActions('taskManagementLog', [
      'DOWNLOAD_IMPORT_TEMPLATE',
      'PUT_SEARCH_HISTORY',
      'GET_SEARCH',
      'GET_HISTROY',
      'JUMP_JUDGES',
      'POST_EVENTES_FORM',
      'DOWNLOAD_JSONFILE',
      'DOWNLOAD_JSONFILE_All',
      'GET_ECHARTS',
      'POST_ECHART_JSON',
      'GET_HANDLE_SORT',
      'GET_LABEL_GROUP',
      'GET_FILTER_GROUP',
      'GET_TASK_LOG_NUM',
      'GET_RISK_TIME',
      'DOWNLOAD_EXCELFILE',
      'DOWNLOAD_EXCELFILE_ALL',
      'FILE_IMPORT',
      'GET_LOCATION',
      'GET_FILTER_GROUP_OTHER',
      // 获取日志类型中英对照
      'GET_STYPE_DICT'
    ]),
    ...mapMutations('taskManagementLog', [
      'SET_LAST_LOGTYPE',
      'SET_LOGTYPE',
      'SET_RAWDATA',
      'SET_HANDLEDATA',
      'SET_LODING',
      'SET_DAYRANGE',
      'SET_TIMERANGE',
      'SET_SEARCHINPUT_ES',
      'SET_SEARCHINPUT_TEXT',
      'SET_GROUP_CHOOSE',
      'SET_MORE_VISIABLE',
      'SET_GROUPDETAIL_VISIABLE',
      'SET_ALERT_CONDITION',
      'SET_CURRENTSIZE',
      'SET_CURRENTPAGE',
      'CLEAR_GROUPDETAIL_VISIABLE',
      'CLEAR_FILTER',
      'SET_DETAIL_INFO'
    ]),
    // 获取项目配置
    getProjectConfig (name) {
      return getProjectConfig(name)
    },
    // 清空搜索框
    clearInput () {
      this.searchInput = ''
    },
    // 更新时间选择器的值
    onDateRangeChange (value) {
      this.SET_TIMERANGE(value)
    },
    // 搜索
    onSearch (type) {
      this.SET_SEARCHINPUT_ES(this.searchInput)
      // 复位当前页数
      if (type !== 'sizeChange') {
        this.SET_CURRENTPAGE(1)
      }
      this.GET_SEARCH(type)
      this.GET_HISTROY()
    },
    // 提交导出事件
    confirmExportEvent () {
      // 表格无数据时，提示暂无可导出数据
      if (this.pagination.total <= 0) {
        this.$notify.error({
          title: '暂无可导出数据'
        })
      } else {
        if (this.exportInfo.amount === '1') {
        // 导出选中
          if (this.totalSelectedItem.length === 0) {
            this.$notify({
              title: '警告',
              message: '没有选中文本',
              type: 'warning'
            })
          } else {
            if (this.exportInfo.type === '4') {
              this.DOWNLOAD_JSONFILE(this.totalSelectedItem)
            } else {
            // excel
              this.DOWNLOAD_EXCELFILE(this.totalSelectedItem)
            }
          }
        } else {
        // 导出全部
          if (this.exportInfo.type === '4') {
            this.DOWNLOAD_JSONFILE_All()
          } else {
          // excel
            this.DOWNLOAD_EXCELFILE_ALL()
          }
        }
      }
      this.stateCtrl.fileExportVisible = false
    },
    // 主table排序
    handleSortChange ({ prop, order }) {
      this.SET_CURRENTPAGE(1)
      this.GET_HANDLE_SORT({
        prop: prop,
        order: order
      })
    },
    // 主table勾选
    handleSelectionChange (value) {
      this.totalSelectedItem = value
    },
    // 每页显示条目改变
    handleSizeChange (value) {
      this.SET_CURRENTPAGE(1)
      this.SET_CURRENTSIZE(value)
      this.onSearch('sizeChange')
    },
    // 当前页改变
    handleCurrentChange (value) {
      // 设置当前页
      this.SET_CURRENTPAGE(value)
      // 生成对应es搜索语句
      this.SET_SEARCHINPUT_ES(this.searchInput)
      // 存在聚合过滤
      if (this.stateCtrl.labelGroupVisible) {
        this.GET_SEARCH('filter')
      } else {
        this.GET_SEARCH('search')
      }
    },
    // 查看日志详情
    jumpDetail (row, event) {
      // 鼠标点击任意一行
      if (event.type === 'default') {
        // 设置原始数据
        this.SET_RAWDATA(row)
        // 处理后数据
        this.SET_HANDLEDATA(initDetail(row._source))
        this.GET_STYPE_DICT()
        // 设置详情页显示内容
        let info = detailInfoStructure({ stype: row._source.stype, handleData: this.handleData, stypeDict: this.stypeDict })
        this.SET_DETAIL_INFO(info)
        this.detailHandleData.projectCtrl = this.projectCtrl
        this.$router.push({
          path: '/business/task/taskFeedBackDetail/' + row._id
        })
      }
    }
  },
  computed: {
    ...mapState({ project: state => state.system.project,
      changeSizeValue: state => state.system.changeSizeValue
    }),
    ...mapGetters('taskManagementLog', [
      'groupPicData',
      'groupData',
      'filterData',
      'filterDataCopy',
      'filterCategory',
      'groupCategory',
      'tableData',
      'handleData',
      'pagination',
      'history',
      'loadingCtrl',
      'alertCondition',
      // 大的日志类型，攻击、脆弱性、异常、运行状态、全部
      'logType',
      'lastLogType',
      'location',
      // 筛选条件 日志类型
      'stypeDict'
    ]),
    // 时间选择器显示的时间
    dayRange: {
      get () {
        return this.$store.state.taskManagementLog.dayRange
      },
      set (value) {
        this.SET_DAYRANGE(value)
      }
    },
    // 搜索框
    searchInput: {
      get () {
        return this.$store.state.taskManagementLog.searchInput
      },
      set (value) {
        this.SET_SEARCHINPUT_TEXT(value)
      }
    },
    // 标签聚合checkbox选择状态
    choose: {
      get () {
        return this.$store.state.taskManagementLog.choose
      },
      set (value) {
        this.SET_GROUP_CHOOSE(value)
      }
    }
  },
  watch: {
    // 项目配置
    project () {
      let projectConfig = this.getProjectConfig(this.project.name)
      for (let index in projectConfig) {
        this.projectCtrl[index] = projectConfig[index]
      }
    }
  }
}
</script>

<style src="./index.less" lang='less'>
</style>
